package com.blog.controller;


import com.blog.pojo.Article;
import com.blog.pojo.Articleid_and_lableid_userid;
import com.blog.pojo.User;
import com.blog.service.ArticleService;
import com.blog.service.Articleid_and_lableid_useridService;
import com.blog.util.UUIdGenId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("article.api")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private Articleid_and_lableid_useridService articleid_and_lableid_useridService;

    Map<String, Object> code = new HashMap<>();

    @ResponseBody
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Map<String, Object> upString(HttpServletRequest request) throws Exception {
        System.out.println("up");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> Map = new HashMap<String, Object>();
        User user = (User) request.getSession().getAttribute("user");

        if (user == null) {
            Map.put("code", "1");
            Map.put("msg", "请登录");
            return Map;
        }


        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();//文件集合


//			if(!file.isEmpty()){
        //上传文件路径
        String path = request.getSession().getServletContext().getRealPath(
                "/resource/upload/siteHeadImage/" + user.getId() + "/");
        //"D:/javaspring框架/FileUpload/WebContent/WEB-INF/imag";
        System.err.println(path);
        // 检查目录
        File uploadDir = new File(path);
        if (!uploadDir.isDirectory()) {
            // 如果不存在，创建文件夹
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
        }

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
            String date = df2.format(new Date());
            System.err.println(date + "当前时间");
            MultipartFile file2 = entity.getValue();
            String filename = file2.getOriginalFilename();

            File filepath = new File(path, filename);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }


            //重命名
            // 扩展名
            String fileExt = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();//扩展名
            //新的文件名
            String newFileName = date + "_" + user.getAccount() + "." + fileExt;
            System.err.println("新文件名：" + newFileName);
            //request.getContextPath()
            //保存的路径
            String Savepath = "/resource/upload/siteHeadImage/" + user.getId() + "/" + newFileName ;
            System.out.println("存储路径" + Savepath);

//            pictureDao.insertPicture(date2,newFileName,Savepath);
            //将上传的文件保存到目标文件中
            file2.transferTo(new File(path + File.separator + newFileName));
            System.out.println("将上传的文件保存到目标文件中" + path + File.separator + filename);

            System.out.println(path);

            resultMap.put("code", 0);
            resultMap.put("msg", "success");
            resultMap.put("src", Savepath);
            Map.put("src", path);
            resultMap.put("data", Map);
        }
        return resultMap;

    }

    @ResponseBody
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public Object addArticle(Article article, HttpSession session) {
        User user = (User) session.getAttribute("user");

        if (user == null) {
            code.put("code", "1");
            code.put("msg", "请登录");
            return code;
        }

        String articleId = UUIdGenId.getId();
        article.setId(articleId);
        article.setUser_id(user.getId());
        System.out.println(article);

        boolean add = articleService.add(article);

        if (add) {
            String articleid_and_lableid_useridId = UUIdGenId.getId();

            com.blog.pojo.Articleid_and_lableid_userid articleid_and_lableid_userid = new Articleid_and_lableid_userid();
            articleid_and_lableid_userid.setId(articleid_and_lableid_useridId);
            articleid_and_lableid_userid.setPassword(article.getPassword());
            articleid_and_lableid_userid.setUser_id(article.getUser_id());
            articleid_and_lableid_userid.setArticle_id(articleId);
            articleid_and_lableid_userid.setLabel_id(article.getLabel_id());
            boolean b = articleid_and_lableid_useridService.byId_CreateLabelAndArticleAndUser(articleid_and_lableid_userid);
           if(b) {
               code.put("a",article);
               code.put("b",articleid_and_lableid_userid);
               return code;
           }else {
               return "添加成功了,但似乎有些异常,似乎是添加时候某参数或算法冲突,请联系管理员吧";
           }
        } else {
            return null;
        }
    }
}
